$(document).ready(function() {
    document.getElementById("map_canvas").style.height  = (document.documentElement.clientHeight-48) + "px";
    document.getElementById("map_canvas").style.width  = (document.documentElement.clientWidth) + "px";

    $("#overlayform").hide();
    $('#cancel').button().click(function() {
        $("#overlayform").hide('slow');
        $('#add').show();
        $('#edit').show();

        // clear fields
        $("#overlay_form").clearForm();
    });

    $('#save').button().click(function(){
        preSubmit();
    });

});

$(window).resize(function() {
    document.getElementById("map_canvas").style.height  = (document.documentElement.clientHeight-48) + "px";
    document.getElementById("map_canvas").style.width  = (document.documentElement.clientWidth) + "px";
});

function addOverlay() {
    $("#overlayform").toggle('slow', function() {
        if ($('#add').html() == 'Add') {
            $('#add').hide();
            $('#edit').hide();
        } else {
            $('#add').show();
        }
    });

    // set empty overlayid
    $('#researchoverlay_id').val();
}

function editOverlay() {
    $("#overlayform").toggle('slow', function() {
        if ($('#edit').html() == 'Edit') {
            $('#edit').hide();
            $('#add').hide();
        } else {
            $('#edit').show();
        }
    });

    // fill the values
    var selectedOverlay = document.getElementById("overlayimg").options[document.getElementById("overlayimg").selectedIndex].value;

    $.ajax({
        type: "GET",
        url: "/data/getOverlayData/overlayid/" + selectedOverlay,
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
            setFieldValues(data);
            return true;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("error: " + textStatus + ", " + errorThrown);
            return false;
        }
    });
}

function preSubmit() {
    if (overlayArray.length == 0) return;

    $('#researchoverlay_slat').val(overlayArray[0].getBounds().getSouthWest().lat());
    $('#researchoverlay_nlat').val(overlayArray[0].getBounds().getNorthEast().lat());
    $('#researchoverlay_wlng').val(overlayArray[0].getBounds().getSouthWest().lng());
    $('#researchoverlay_elng').val(overlayArray[0].getBounds().getNorthEast().lng());
}

function setFieldValues(data) {
//        alert(data['overlaytitle']);

    $('#researchoverlay_id').val(data['id']);
    $('#researchoverlay_researchid').val(data['researchid']);
    $('#researchoverlay_overlaytitle').val(data['overlaytitle']);
    $('#researchoverlay_overlaydescription').val(data['overlaydescription']);
    $('#researchoverlay_slat').val(data['slat']);
    $('#researchoverlay_nlat').val(data['nlat']);
    $('#researchoverlay_wlng').val(data['wlng']);
    $('#researchoverlay_elng').val(data['nlng']);
}

/**
 * Groundoverlaysizer (Gmap version2):
 * http://code.google.com/p/gmaps-samples/source/browse/trunk/groundoverlay/groundoverlaysizer2.html?r=2328
 */

var map = null;

var marker_NE;
var marker_SW;
var marker_move;

var border;
var groundOverlay;

var icon_NE;
var icon_SW;
var icon_move;

var geocoder = null;

var overlayOpacity = 70;

function onLoad(id) {
    if (groundOverlay != null) {
        groundOverlay.setMap(null);
    }
    deleteOverlaysImages();

    var myOptions = {
        zoom: 4,
        center: new google.maps.LatLng(20.280232,38.512573),
//            panControl: true,
//            mapTypeControl: true,
        mapTypeId: google.maps.MapTypeId.SATELLITE
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    google.maps.event.addListener(map, "mousemove", moveFunc);

    function moveFunc(event){
        $("#overlayimageeditCoordinates").html("Overlay Image ("+event.latLng.lat().toFixed(6)+", "+event.latLng.lng().toFixed(6)+")");
    }
    
    if(id != null){
        groundOverlay = setOverlayImageWithOpacity(map, id, overlayOpacity);
        return;
    }

//        if(document.getElementById("theUrl") == null)
//            return;

//        initResizer();





}

function initResizer(){
    icon_NE = new google.maps.MarkerImage();
    icon_NE.url = 'http://imagine-it.org/google/marker_NE_icon.png';
    icon_NE.size = new google.maps.Size(32, 32);
    icon_NE.anchor = new google.maps.Point(22, 10);

    icon_SW = new google.maps.MarkerImage();
    icon_SW.url = 'http://imagine-it.org/google/marker_SW_icon.png';
    icon_SW.size = new google.maps.Size(32, 32);
    icon_SW.anchor = new google.maps.Point(6, 20);

    icon_move = new google.maps.MarkerImage();
    icon_move.url = 'http://imagine-it.org/google/marker_move_icon.png';
    icon_move.size = new google.maps.Size(32, 32);
    icon_move.anchor = new google.maps.Point(6, 20);

    setTimeout(function(){
        initialPosition();
    }, 1000);
}

function initialPosition() {

    //clear overlays
    clearAllMarkers();

    var newBounds;
    if (overlayArray.length == 0) {
        var bounds = map.getBounds();

        var span = bounds.toSpan();
        var newSW = new google.maps.LatLng(bounds.getSouthWest().lat() + span.lat()/5,
            bounds.getSouthWest().lng() + span.lng()/5);
        var newNE = new google.maps.LatLng(bounds.getNorthEast().lat() - span.lat()/5,
            bounds.getNorthEast().lng() - span.lng()/5);

        newBounds = new google.maps.LatLngBounds(newSW, newNE);
    } else {
        newBounds = overlayArray[0].bounds_;
    }

    marker_NE = new google.maps.Marker({
        position: newBounds.getNorthEast(),
        map: map,
        draggable: true,
        icon: icon_NE
    });

    google.maps.event.addListener(marker_NE, 'drag', function() {
        updatePolyline();
    });

    marker_SW = new google.maps.Marker({
        position: newBounds.getSouthWest(),
        map: map,
        draggable: true,
        icon: icon_SW
    });

    google.maps.event.addListener(marker_SW, 'drag', function() {
        updatePolyline();
    });

    marker_move = new google.maps.Marker({
        position: new google.maps.LatLng(
            (marker_SW.getPosition().lat() + marker_NE.getPosition().lat()) / 2, (marker_NE.getPosition().lng() + marker_SW.getPosition().lng()) / 2),
        map: map,
        draggable: true,
        icon: icon_move
    });

    google.maps.event.addListener(marker_move, 'drag', function() {updatePolyline() ;}) ;

    marker_move.savedPosition = marker_move.getPosition();			// Save for later

    updatePolyline();

}

function updatePolyline() {
    if (border) {
        border.setMap(null);
    }

    // Check for moved center...

    if ( marker_move.getPosition() != marker_move.savedPosition )
    {
        var x = marker_move.getPosition().lat() - marker_move.savedPosition.lat() ;
        var y = marker_move.getPosition().lng() - marker_move.savedPosition.lng() ;
        marker_SW.setPosition( new google.maps.LatLng( marker_SW.getPosition().lat() + x, marker_SW.getPosition().lng() + y) ) ;
        marker_NE.setPosition( new google.maps.LatLng( marker_NE.getPosition().lat() + x, marker_NE.getPosition().lng() + y) ) ;

    } else						// Center not moved so move center
    {
        var x = (marker_SW.getPosition().lat() + marker_NE.getPosition().lat()) / 2 ;
        var y = (marker_NE.getPosition().lng() + marker_SW.getPosition().lng()) / 2 ;
        marker_move.setPosition( new google.maps.LatLng(x,y) ) ;
    }

    marker_move.savedPosition = marker_move.getPosition() ;			// Save for later

    var points = [
        marker_NE.getPosition(),
        new google.maps.LatLng(marker_SW.getPosition().lat(), marker_NE.getPosition().lng()),
        marker_SW.getPosition(),
        new google.maps.LatLng(marker_NE.getPosition().lat(), marker_SW.getPosition().lng()),
        marker_NE.getPosition()];

    border = new google.maps.Polyline({
        path: points,
        strokeColor: "#fff600",
        strokeWeight: "5px"
    });

    border.setMap(map);

    updateGroundOverlay();
}

function updateGroundOverlay() {
    if (groundOverlay != null) {
        groundOverlay.setMap(null);
    }

    deleteOverlaysImages();

    var selectedOverlay = document.getElementById("overlayimg").options[document.getElementById("overlayimg").selectedIndex].value;

    groundOverlay = new ProjectedOverlay(map,
        "/map/overlay_Image?overlayid=" + selectedOverlay,
        new google.maps.LatLngBounds(marker_SW.getPosition(), marker_NE.getPosition()),
        {'percentOpacity' : overlayOpacity}
    );

    overlayArray.push(groundOverlay);

}

function clearAllMarkers() {

    //clear overlays
    if (marker_NE) {
        marker_NE.setMap(null);
        marker_NE = null;
    }
    if (marker_SW) {
        marker_SW.setMap(null);
        marker_SW = null;
    }
    if (marker_move) {
        marker_move.setMap(null);
        marker_SW = null;
    }
    if (border) {
        border.setMap(null);
        border = null;
    }
}

function displayOverlay(overlayid) {
    deleteOverlaysImages();
    clearAllMarkers();
    groundOverlay = setOverlayImageWithOpacity(map, overlayid, overlayOpacity);
}

function saveOverlay() {
    var selectedOverlay = document.getElementById("overlayimg").options[document.getElementById("overlayimg").selectedIndex].value;

    $.ajax({
        type: "POST",
        url: "/redsea20_dev.php/data/updateOverlay/overlayid/" + selectedOverlay,
        data: {slat: overlayArray[0].getBounds().getSouthWest().lat(),
            nlat: overlayArray[0].getBounds().getNorthEast().lat(),
            wlng: overlayArray[0].getBounds().getSouthWest().lng(),
            elng: overlayArray[0].getBounds().getNorthEast().lng()
        },
        dataType: "html",
        success: function(data, textStatus, jqXHR) {
            alert('Overlay data saved.');
            return false;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("error: " + textStatus + ", " + errorThrown);
            return false;
        }
    });
}

function deleteOverlay(){
    var isConfirm = confirm('Are you sure to delete this overlay?');
    if (isConfirm) {
        var selectedOverlay = document.getElementById("overlayimg").options[document.getElementById("overlayimg").selectedIndex].value;
         window.location = "/data/deleteOverlay/overlayid/" + selectedOverlay;
    } else {

    }
}
